# Load packages
library(readr)
# Set seed
set.seed(1996)
#############################
rm(list=setdiff(ls(), c('script', 'scripts', 'log_file')))
#############################
# Load Master Data on candidates running
master <- readRDS('master.rds')

# Load DIME Data (accessed 9-24-2024 from https://data.stanford.edu/dime)
load('dime_recipients_1979_2022.rdata')

# Subset to only Democrats and Republican candidates for US House, 2018-2022
# Remove unwanted variables
dime <- subset(cands, seat == 'federal:house' & cycle >= 2018 & 
                 (party == 200|party == 100) & state != 'PR'& state != 'VI'
               & !is.na(Cand.ID),
               select = c('ICPSR2', 'Cand.ID', 'recipient.cfscore.dyn', 'cycle',
                          'num.givers'))

# Rename columns to merge with master df
colnames(dime) <- c('icpsr', 'FECCandID', 'cfscore', 'year', 'num_donors')

# Ensure CFscores set to missing if fewer than 25 donors
# consistent with Bonica (2014)
dime$cfscore <- ifelse(dime$num_donors <= 25, NA, dime$cfscore)

# Merge with master by FECCandID and Year
# Keep observations without an FECCandID that will not match
master <- merge(master, dime, by = c('FECCandID', 'year'), all.x = TRUE)

# Load VoteView Data (accessed 9-16-2024 from https://voteview.com/data)
voteview <- read.csv('Hall_members.csv')

# Subset to only corresponding congresses and remove unwanted variables
voteview <- subset(voteview, congress == 115|congress == 116|congress == 117, 
                   select = c('congress', 'icpsr',
                              'bioguide_id', 'nominate_dim1'))

# Add year variable for merging
voteview$year <- NA
voteview$year[voteview$congress == 115] <- 2018
voteview$year[voteview$congress == 116] <- 2020
voteview$year[voteview$congress == 117] <- 2022

# Merge with Master by icpsr and year
master <- merge(master, voteview, by = c('icpsr', 'year'), all.x = TRUE)
rm(cands, dime, voteview)

# Load in Ideological Caucua Membership
caucus <- read.csv('Caucus_membership.csv')

# Merge with Caucus Information for Incumbents 
master <- merge(master, caucus, all.x = TRUE, c('state_postal', 
                                                'cd', 
                                                'cand_party',
                                                'year',
                                                'candidate'))

# Save master_withCFNom.rds
write_rds(master, 'master_withCFNom.rds')


































